package com.netty.learn.udpdemo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClient {
	
	private String sendStr = "SendString";
	private String netAddress = "127.0.0.1";
	private final int PORT_NUM = 5066;
	
	private DatagramSocket datagramSocket;
	private DatagramPacket datagramPacket;
	
	public UdpClient() {
		try {
			datagramSocket = new DatagramSocket();
			byte[] buf = sendStr.getBytes();
			InetAddress address = InetAddress.getByName(netAddress);
			datagramPacket = new DatagramPacket(buf, buf.length, address, PORT_NUM);
			datagramSocket.send(datagramPacket);
			
			//接受数据
			byte[] receBuf = new byte[1024];
			DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length);
			datagramSocket.receive(recePacket);
			
			String receStr = new String(recePacket.getData(), 0 , recePacket.getLength());
            System.out.println("Client Rece Ack:" + receStr);
            System.out.println(recePacket.getPort());
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (datagramSocket != null) {
				datagramSocket.close();
			}
		}
	}
	public static void main(String[] args) {
		new UdpClient();
	}

}
